//
//  ViewController.m
//  DatePickView
//
//  Created by 伍银荣 on 2021/6/20.
//  Copyright © 2021 com.example. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) UIToolbar *toolBar;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.textField.inputView = self.datePicker;
    self.textField.inputAccessoryView = self.toolBar;
}

-(UIDatePicker *)datePicker {
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc]init];
        //设置datePickView的模式
        _datePicker.datePickerMode = UIDatePickerModeDate;
        //设置日期区域控件为简体中文
        _datePicker.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh-Hans"];
    }
    return _datePicker;
}

- (UIToolbar *)toolBar {
    if (!_toolBar) {
        _toolBar = [[UIToolbar alloc]init];
        //一定要设置frame,不然出不来,只设置宽高就可以了
        _toolBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
        UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancleItemClicked)];
        UIBarButtonItem *flexItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem *confirmItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(confirmItemClicked)];
        _toolBar.items = @[cancelItem, flexItem,confirmItem];
    }
    return _toolBar;
}

- (void)cancleItemClicked {
    NSLog(@"取消");
    //将键盘弹回去(取消第一响应者)
    [self.view endEditing:YES];
}


- (void)confirmItemClicked {
    NSLog(@"确定");
    //拿到当前滚动的时间
    NSDate *date = self.datePicker.date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    //转换日期格式
    formatter.dateFormat = @"yyyy年MM月dd日";
    NSString *dateStr = [formatter stringFromDate:date];
    self.textField.text = dateStr;
    [self.view endEditing:YES];
}


@end
